package org.gwu.seuss.communication.sockets.ssl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Properties;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class ServerSocket {

	public static SSLServerSocket createSSLSocket(String propertiesResource, int port, char[] storePassword) {

		try {
			Properties properties = Util.loadPropertiesFromResource(propertiesResource);

			SystemProperties.initSystemProperties(properties, storePassword,storePassword);

			try (InputStream keyStoreInputStream = new FileInputStream(properties.getProperty(SystemProperties.KEYSTORE_PROP_KEY))) {

				ManagerPair<KeyManagerFactory, KeyStore> pair = Util.getInitKeyFactory(keyStoreInputStream,String.copyValueOf(storePassword), "JKS");
				TrustManagerFactory tmf = Util.getInitTrustFactory(pair.getStore());
				
				SSLContext ctx = SSLContext.getInstance("SSL");
				ctx.init(pair.getFactory().getKeyManagers(),tmf.getTrustManagers(), null);

				SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
				SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(port);
				sslserversocket.setEnabledCipherSuites(Util.CIPHERSUITE);
			
				return sslserversocket;

			} catch (Exception ex) {
				throw ex;
			}

		} catch (Exception ex) {
			throw new IllegalStateException("Unable to create server socket",ex);
		}
	}

}
